<template>
  <div class="login-container">
    <h2>数字孪生水网平台</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLogin" style="width: 100%">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useMainStore } from '@/stores/mainStore';
import { systemApi } from '@/api/system';
import md5 from 'blueimp-md5';
import router from '@/router';


const store = useMainStore();

const formRef = ref();
const form = ref({
  username: '',
  password: '',
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const onLogin = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    try {
      const encryptedPwd = md5(form.value.password);
       systemApi.loginByUserName({username:form.value.username,password:encryptedPwd}).then((data) => {  
           store.setToken(data.substr(7));
          systemApi.getUserInfo().then((res) => {
                debugger;
                   store.setUserinfo(res);
                  router.push({ path: '/home' });
          });
          
      })

    } catch (e) {
      console.error('登录异常:', e);
      ElMessage.error('登录失败，请稍后再试');
    }
  });
};
</script>

<style scoped>
.login-container {
  width: 400px;
  margin: 120px auto;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style>
